/*
 * 数据请求
 */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "@ohos/axios";

// axios 请求配置
const config = {
  baseURL:'http://192.168.1.130:3000',
  // baseURL:'http://10.10.23.154:3000',
  // baseURL: '/api',
  timeout: 1000
}

// 定义返回值类型
interface Result<T = any> {
  data: T;
}

class Http {
  // axios 实例
  private instance: AxiosInstance;
  // 构造函数初始化
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    //定义拦截器
    this.interceptors();
  }

  private interceptors() {
    // axios 发送请求之前的处理
    this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      // 在请求头部携带token
      let token = '';
      if (token) {
        config.headers!['token'] = token;
      }
      return config;
    }, (error: any) => {
      error.data = {};
      error.data.msg = '服务器异常，请联系管理员！'
      return error;
    })
    // axios 请求返回之后的处理
    // 请求返回处理
    this.instance.interceptors.response.use((res: AxiosResponse) => {
      return res.data;
    }, (error) => {
      console.log('进入错误！');
      error.data = {};
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.data.msg = "错误请求";
            console.log(error.data.msg);
            break;
          case 401:
            error.data.msg = "未授权，请登录";
            console.log(error.data.msg);
            break;
          case 500:
            error.data.msg = "服务器端出错";
            console.log(error.data.msg);
            break;
          default:
            error.data.msg = `连接错误${error.response.status}`;
            console.log(error.data.msg);
        }
      } else {
        error.data.msg = "连接到服务器失败";
        console.log(error.data.msg)
      }
      return Promise.reject(error);
    })
  }
  // GET方法
  get<T = Result>(url: string, params?: object): Promise<T> {
    return this.instance.get(url, { params });
  }
  // POST方法
  post<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.post(url, data);
  }
  // PUT方法
  put<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.put(url, data);
  }
  // DELETE方法
  delete<T = Result>(url: string): Promise<T> {
    return this.instance.delete(url);
  }
}

export default new Http(config);